<template>
  <div>
    <van-search
    v-model.trim ="searchText"
    shape="round"
     show-action label="地址"
     placeholder="请输入搜索关键词"
      background="skyblue"
      @search="onSearch">
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <div class="history-title">
      <van-icon class="iconfont" class-prefix="icon" name="sousuo" size="17px"></van-icon>
      <span>历史记录</span>
    </div>
    <ul class="history-text">
      <li  v-for='his in histories' :key="his" @click="clickHis(his)">{{his}}</li>
    </ul>
    <empty v-if="histories.length===0"/>
  </div>
</template>

<script>
import Empty from '@/components/Empty'
export default {
  data () {
    return {
      histories: localStorage.getItem('his') ? JSON.parse(localStorage.getItem('his')) : [],
      searchText: ''
    }
  },
  methods: {
    clickHis (his) {
      this.$router.push({
        path: '/searchResult',
        query: {
          word: his
        }
      })
    },
    onSearch () {
      if (this.searchText === '') {
        this.$toast('不能为空哦')
        return
      }
      const his = localStorage.getItem('his') ? JSON.parse(localStorage.getItem('his')) : []
      // 若重复，删除之前的，添加最新的
      const index = his.indexOf(this.searchText)
      if (index !== -1) {
        // 不重复
        his.splice(index, 1)
      }
      his.unshift(this.searchText)
      // 限制长度
      if (his.length > 5) {
        his.pop()
      }
      localStorage.setItem('his', JSON.stringify(his))
      // 跳转页面
      this.$router.push({
        path: '/searchResult',
        query: {
          word: this.searchText
        }
      })
    }
  },
  components: {
    Empty
  }
}
</script>

<style lang="scss" scoped>
.history-title{
  width: 100%;
  padding: 10px;
  box-sizing: border-box;
  span{
    font-size: 14px;
  }
}
.history-text{
  display: flex;
  flex-wrap: wrap;
  li{
    list-style: none;
    height: 28px;
    line-height: 28px;
    margin: .2rem .3rem;
    padding: 0 .6rem;
    border-radius: 20px;
    background: #f3f5f7;
    font-size: 14px;
    text-align: center;
  }
}

</style>
